/**
 * Created by zhangsong on 2019-01-19.
 */

const fs = require('fs');
const path = require('path');
const moment = require('moment');
const config = require('../config/index');
const ResultDAO = require('../dao/result');

const LIMIT = 100;

fs.mkdirSync(config.output, { recursive: true });

async function insert({ file, point = 0, date }) {
  const list = await ResultDAO.findByPage({ date, point, limit: LIMIT });
  const text = list.reduce((prev, next) => {
    return prev + `${next.point},${next.level}
`;
  }, '');
  fs.appendFileSync(file, text, 'utf8');
  if (list.length === LIMIT) { // 如果还有数据,继续查询
    await insert({ file, point: list[list.length - 1].point, date });
  }
}

(async function main() {
  const list = fs.readdirSync(config.input);
  for (let i = 0; i < list.length; i++) {
    const name = list[i].substring(0, list[i].indexOf('.'));
    const date = moment(name).format('YYYY-MM-DD');
    const file = path.join(config.output, `${date}.txt`);
    fs.appendFileSync(file, `pointid,灾害程度
`, 'utf8');
    await insert({ file, date });
    console.log(`${date} 数据已准备导出.执行下一个日期`);
  }
})();
